package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/gookit/event"
	"github.com/vueadmin/app/admin/dto"
	"github.com/vueadmin/app/admin/service"
	"github.com/vueadmin/pkg/captcha"
	"github.com/vueadmin/pkg/jwt"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/common/result"
	"github.com/vueadmin/utils/response"
	"strings"
)

var AdminLogin = new(adminLogin)

type adminLogin struct{}

// 登录方法
func (adminLogin) Login(c *gin.Context) {
	req := dto.AdminLoginReq{}
	if err := utils.BindAndValid(c, &req); err != nil {
		response.Fail(c, err.Error())
		return
	}
	info, err := service.AdminLoginService.Login(&req)
	if err != nil {
		response.Err(c, err)
		return
	}
	info.Access = strings.Join(info.Role.Access, ",")

	token, error := jwt.NewJwt("admin").CreateToken(info)
	if error != nil {
		response.Fail(c, "token生成失败")
		return
	}
	event.MustFire("adminLoginEvent", event.M{
		"user":   info.User,
		"token":  token,
		"handle": c,
	})
	response.Success(c, "登陆成功", token)
}

// 验证码
func (adminLogin) Captcha(c *gin.Context) {
	response.Success(c, "success", result.M{
		"captcha":     captcha.Generate(),
		"site_title":  c.MustGet("site_title"),
		"success_url": "/admin/Home/index",
	})
}
